﻿using Base.EFCore.Base;
using Base.EFCore.Entity;
using Microsoft.EntityFrameworkCore;
using System.Data;
namespace Base.EFCore
{
    public class EFContext : DbContext
    {
        public EFContext() { }
        public EFContext(DbContextOptions options) : base(options)
        {

        }

        public virtual DbSet<Material> Materials { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseCollation("utf8_general_ci")
                .HasCharSet("utf8");
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(Material).Assembly);
            base.OnModelCreating(modelBuilder);
        }

        public override int SaveChanges()
        {
            ChangeTracker.Entries().Where(p => (p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified) && p.Entity is BaseEntity).ToList()
           .ForEach(e =>
            {
                if (e.State == EntityState.Added)
                {
                    ((BaseEntity)e.Entity).CreateTime = DateTime.Now;
                    if (((BaseEntity)e.Entity).Id == Guid.Empty)
                        ((BaseEntity)e.Entity).Id = Guid.NewGuid();
                }
                   
                if (e.State == EntityState.Modified)
                    ((BaseEntity)e.Entity).UpdateTime = DateTime.Now;

               ((BaseEntity)e.Entity).BeginSave(e);
            });

            return base.SaveChanges();
        }
    }
}
